package cn.jjxx.modules.sys.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;

import cn.jjxx.core.common.service.impl.CommonServiceImpl;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.utils.ArrayUtils;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.core.utils.http.HttpClientUtils;
import cn.jjxx.modules.sys.entity.Infc;
import cn.jjxx.modules.sys.entity.InfcBarVo;
import cn.jjxx.modules.sys.entity.InfcChartVo;
import cn.jjxx.modules.sys.mapper.InfcMapper;
import cn.jjxx.modules.sys.request.ArtificialHttpServletRequest;
import cn.jjxx.modules.sys.request.InvokeControllerByRequest;
import cn.jjxx.modules.sys.service.IInfcService;

/**   
 * @Title: 接口列表
 * @Description: 接口列表
 * @author jjxx
 * @date 2018-01-13 00:29:11
 * @version V1.0   
 *
 */
@Transactional
@Service("infcService")
public class InfcServiceImpl  extends CommonServiceImpl<InfcMapper,Infc> implements  IInfcService {

    public static final Logger LOGGER = LoggerFactory.getLogger(InfcServiceImpl.class);

    @Autowired
    private InvokeControllerByRequest invokeControllerByRequest;

    private static final String reg = "(\\b(update|delete|insert|trancate|into|declare|drop|execute|alter|modify|change)\\b)";
    private static final Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);

    @Override
    public boolean updateBatch(List<Infc> list) {
        if(list!=null&&list.size()>0){
            return baseMapper.updateBatch(list);
        }
        return true;
    }

    @Override
    public boolean checkSql(String sql) {
        return !sqlPattern.matcher(sql).find();
    }

    @Override
    public AjaxJson infcData(HttpServletRequest request) {
        AjaxJson result = new AjaxJson();

        String code = request.getParameter("code");
        if (StringUtils.isBlank(code)) {
            result.fail("查询失败，code不能为空");
            return result;
        }

        Infc infc = getByCode(code);
        if (infc == null) {
            result.fail("查询失败，code不存在");
            return result;
        }
        if (StringUtils.isNotBlank(infc.getDefinedSql())) {
            infc.setDefinedSql(StringEscapeUtils.unescapeHtml4(infc.getDefinedSql()));
            if (checkSql(infc.getDefinedSql())) {
                Map<String, String[]> parameterMap = request.getParameterMap();
                Map<String, Object> map = Maps.newHashMap();
                for (String key : parameterMap.keySet()) {
                    String[] elements = parameterMap.get(key);
                    if (ArrayUtils.isNotEmpty(elements)) {
                        // 判断是否是数字，如果其中有一项不是数字，全部加单引号
                        boolean isNum = true;
                        for (String element : elements) {
                            isNum = isNumeric(element);
                            if (!isNum) {
                                break;
                            }
                        }
                        String value = "";
                        if (elements.length == 1) {
                            // 单个参数
                            if (isNum) {
                                value = String.join(",", elements);
                            } else {
                                value = Arrays.stream(elements).map(word -> word.split(","))
                                        .flatMap(Arrays::stream).map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
                            }
                        } else {
                            // 多个参数统一都加单引号 如 id=1,2
                            value = Arrays.stream(elements).map(word -> word.split(","))
                                    .flatMap(Arrays::stream).map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
                        }
                        if(!StringUtils.isEmpty(value) && !"''".equals(value)) {//不支持传空值参数
                        	map.put(key, value);
                        }
                    }
                }
                try {
                	String haveParamSql = getSqlWithParams(infc.getDefinedSql(),map);
                    
                    List<LinkedHashMap<String, Object>> retList = baseMapper.selectReport(haveParamSql);
                    if ("1".equals(infc.getReturnType())) {
                        // 单值 只返回固定的 {value:值}
                        if (CollectionUtils.isNotEmpty(retList)) {
                            Map<String, Object> single = Maps.newHashMap();
                            single.put("value", retList.get(0).get("value"));
                            result.setData(single);
                        }
                    } else if ("2".equals(infc.getReturnType())) {
                        // 列表正常返回
                        Object object = buildVo(infc,retList);
                        result.setData(object);
                    }
                } catch (Exception e) {
                    LOGGER.error("接口查询失败，errorMsg{}", e.getMessage());
                }
            } else {
                LOGGER.error("接口查询失败，接口配置错误：SQL非法，code：{}", code);
                result.fail("查询失败，接口配置错误");
                return result;
            }
        } else if (StringUtils.isNotBlank(infc.getInterfaceUrl())) {
            try {
                Object httpResult = getHttpResult(request, infc);
                if (httpResult != null) {
                    if (httpResult instanceof AjaxJson) {
                        return (AjaxJson) httpResult;
                    } else {
                        result.setData(httpResult);
                    }
                } else {
                    result.fail("查询失败，系统异常");
                }
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("查询失败，系统异常，code：{}，errorMsg：{}", code, e.getMessage());
                result.fail("查询失败，系统异常");
            }
        } else {
            result.fail("查询失败，接口未配置");
            return result;
        }

        return result;
    }

    
    /**
     * 根据参数处理sql
     * 参数为null时对应条件语句要删除：如 and name=${name}  这部分全要删除
     * @param definedSql
     * @param map
     * @return
     */
    private static String getSqlWithParams(String definedSql, Map<String, Object> map) {
    	if(null !=map) {
    		for (String key : map.keySet()) {
    			String newkey = key.replace("#", ".");
    			map.put(newkey, map.get(key));
    		}
    	}
        StrSubstitutor strSubstitutor = new StrSubstitutor(map);
        definedSql = strSubstitutor.replace(definedSql);
    	List<String> keys=getKeys(definedSql, map);
        
    	for (String key : keys) {
			// and key = 
			// or key != 
			String reg =" ((and)|(or))(?i)\\s+((\\S\\.)?"+key+ ")(?i)\\s*(=|!=)\\s*\\$\\{\\s*("+key+")(?i)\\s*\\}";
			definedSql = definedSql.replaceAll(reg, "");
		}
		return definedSql;
	}

	/**
	 * 根据占位符找出key 加到列表(仅key不包含${})
	 * @param definedSql
	 * @return
	 */
	private static List<String> getKeys(String definedSql, Map<String, Object> map) {
		List<String> list = new ArrayList<String>();
		String regex="\\$\\{\\s*\\S+\\s*\\}";

	     Pattern pattern = Pattern.compile(regex);
	     Matcher matcher = pattern.matcher(definedSql);
	     while(matcher.find()) {
	    	 String key = matcher.group(0);
			 String fieldName = key.substring(2,key.length()-1);
			 fieldName = fieldName.trim();
			 if(null == map || !map.containsKey(fieldName)) {
				 list.add(fieldName);
			 }
	     }
		return list;
	}
	
	 public static void main(String[] args) { 
		 
		 String sqlString="select qualification_name name, qualification_name title ,	number value from record_qualifications where 1=1  or Number2  != ${number2} and nUmber1  = ${number1} and number  = ${numBer}  order by sort";
		 sqlString="select name   and property=${property} and use_status != ${ use_status}";
		 sqlString ="select  id,name as label, \n"
		 		+ "project_desc as content,\n"
		 		+ "b.FNAME_L2 as flable,tt.ffile as imgPath,\n"
		 		+ "case when LENGTH(tt.ffile)>0 then '1' else '0' end as isbase64\n"
		 		+ "from  eq_project_info p\n"
		 		+ "left join eas_t_org_baseunit b on b.fid=p.org_id\n"
		 		+ "left join (\n"
		 		+ "	select m.*,t.ffile from (\n"
		 		+ "	select fbillid,max(FUploadDate) FUploadDate from t_ec_projectpic group by fbillid\n"
		 		+ "	) m\n"
		 		+ "	left join t_ec_projectpic t on t.fbillid=m.fbillid and t.FUploadDate=m.FUploadDate\n"
		 		+ ") tt on p.id=tt.fbillid\n"
		 		+ "where 1=1 "
		 		+ "and project_type=${project_type} and road_type=${road_type} and engineering_type=${engineering_type} "
		 		+ "and a.id=${id}";
		 System.out.println(sqlString);
		 sqlString = getSqlWithParams(sqlString,null);
		 System.out.println(sqlString);
	 }

	private Object buildVo(Infc infc, List<LinkedHashMap<String, Object>> data) {
        if (null == infc.getChartType() ||  "normal".equals(infc.getChartType())) {
            // 默认 不做处理
            return data;
        }
        List<InfcChartVo> infcChartVoList = Lists.newArrayList();
        if ("bar".equals(infc.getChartType())) {
        	List<LinkedHashMap<String, Object>> list = Lists.newArrayList();
            /*
            柱状图
            [{"id":"01705d06a0724546abff46f928249023","number":"S10","name":"二龙关-镇雄","xname":"龙镇高速","value":["13.63,13.63,13.63,13.63,13.63","13.63,13.63,13.63,13.63,13.63"],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[13.63,13.63],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[13.63,13.63],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[13.63,13.63],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[13.63,13.63],
            "title":["S10","G10"]}]
             */
            for (LinkedHashMap<String, Object> row : data) {
            	LinkedHashMap<String, Object> vo = new LinkedHashMap<>();                
                Object value = row.get("value");

           	 	for (String key: row.keySet()) {
           	 		vo.put(key, row.get(key));
                }
           	 	vo.put("title", Lists.newArrayList(StringUtils.defaultString(infc.getTitle(), "").split(",")));
                if (value != null) {
                    String valueStr = String.valueOf(value);
                    if (valueStr.contains("|")) {
                        vo.put("value",Lists.newArrayList(valueStr.replace("|", "#").split("#")));
                    } else {
                    	vo.put("value",Lists.newArrayList(value.toString()));
                    }
                }
                vo.put("name",StringUtils.defaultString(infc.getXname(), (String) row.get("xname")));
                vo.put("xname",row.containsKey("xname") ? (String) row.get("xname") : infc.getXname());
                vo.put("barWidth",infc.getBarWidth());
                list.add(vo);
            }
            return list;
        }else if ("bar1".equals(infc.getChartType())) {
        	List<List> list = Lists.newArrayList();
            /*
            柱状图
            [
			    [
			        "score",
			        "amount",
			        "product"
			    ],
			    [
			        89.3,  //色
			        58212, //值
			        "Matcha Latte"  //名称
			    ]
    		]
             */
            for (LinkedHashMap<String, Object> row : data) {
            	List<Object> vo = Lists.newArrayList();   
           	 	for (String key: row.keySet()) {
           	 		vo.add(row.get(key));
                }
                list.add(vo);
            }
            return list;
        } else if ("line".equals(infc.getChartType())) {
            /*
            折线图
            [{"id":"01705d06a0724546abff46f928249023","number":"S10","name":"二龙关-镇雄","xname":"龙镇高速","value":["1099,499,123.63,413.63,13.63","888,799,313.63,513.63,13.63"],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[499,799],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[123.63,313.63],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[413.63,513.63],
            "title":["S10","G10"]},{"id":"03d486f1daef4ccda1370137a2f2268b","number":"S84","name":"天柱-镇远","xname":"三施高速","value":[13.63,13.63],
            "title":["S10","G10"]}]
             */
            for (LinkedHashMap<String, Object> row : data) {
                InfcChartVo vo = new InfcChartVo();
                vo.setTitle(Lists.newArrayList(StringUtils.defaultString(infc.getTitle(), "").split(",")));
                Object value = row.get("value");
                if (value != null) {
                    vo.setValue(Lists.newArrayList(String.valueOf(value).replace("|", "#").split("#")));
                }
                vo.setName(StringUtils.defaultString(infc.getXname(), (String) row.get("xname")));
                vo.setXname(row.containsKey("xname") ? (String) row.get("xname") : infc.getXname());
                vo.setBarWidth(infc.getBarWidth());
                infcChartVoList.add(vo);
            }
        } else if ("pie".equals(infc.getChartType())) {
            /*
            饼图
            [{"name":"27%","title":"0-2年","value":326.723},
            {"name":"47%","title":"3-5年","value":576.57},
            {"name":"20%","title":"6-8年","value":247.442},
            {"name":"6%","title":"9-10年","value":76.096}]
             */
            for (LinkedHashMap<String, Object> row : data) {
                InfcChartVo vo = new InfcChartVo();
                vo.setName(StringUtils.defaultIfBlank(infc.getXname(), (String) row.get("xname")));
                vo.setTitle(StringUtils.defaultIfBlank(infc.getTitle(), (String) row.get("title")));
                Object value = row.get("value");
                vo.setValue(String.valueOf(value));
                infcChartVoList.add(vo);
            }
        } else if ("pie3d".equals(infc.getChartType())) {
            // 饼图3d
        	return toChartBin(data);
        } else if ("table".equals(infc.getChartType())) {
            // 表格
            return data;
        } else if ("scatterplot".equals(infc.getChartType())) {
            /*
            散点图
            [
                {"name":"男性","value":[[160,60],[170,64],[180,72],[190,75],[200,82]]},
                {"name":"女性","value":[[155,39],[160,45],[170,48],[180,55],[190,60]]}
            ]
             */
            for (LinkedHashMap<String, Object> row : data) {
                InfcChartVo vo = new InfcChartVo();
                vo.setName(StringUtils.defaultString(infc.getXname(), (String) row.get("xname")));
                Object value = row.get("value");
                if (value != null) {
                    vo.setValue(Lists.newArrayList(String.valueOf(value).replace("|", "#").split("#")));
                }
                infcChartVoList.add(vo);
            }
        } else if ("waterwave".equals(infc.getChartType())) {
            /*
            水波图
            {"data":[0.2,0.2,0.7,0.5],"title":"22人数值"}
             */
            InfcChartVo vo = new InfcChartVo();
            vo.setTitle(infc.getTitle());
            List<Object> dataList = Lists.newArrayList();
            for (LinkedHashMap<String, Object> row : data) {
                Object value = row.get("value");
                if (value != null) {
                    dataList.add(value);
                }
            }
            vo.setData(dataList);
            return vo;
        } else if ("transversebar".equals(infc.getChartType())) {
            /*
            横向柱状图
            [{"xname":"龙镇高速","value":["13.63"],"title":["S10"]},
            {"xname":"三施高速","value":[19.63],"title":["S10"]}]
             */
            for (LinkedHashMap<String, Object> row : data) {
                InfcChartVo vo = new InfcChartVo();
                vo.setTitle(Lists.newArrayList(StringUtils.defaultIfBlank(infc.getTitle(), (String) row.get("title"))));
                Object value = row.get("value");
                if (value != null) {
                    vo.setValue(Lists.newArrayList(String.valueOf(value).replace("|", "#").split("#")));
                }
                vo.setXname(row.containsKey("xname") ? (String) row.get("xname") : infc.getXname());
                vo.setBarWidth(infc.getBarWidth());
                infcChartVoList.add(vo);
            }
        } else if ("progressbar".equals(infc.getChartType())) {
            /*
            横向柱状图
            [ {
		        "label": "贵州省XXX公路XXX年日常维护",
		        "bar1": {
		            "precent": 80,
		            "value": 4
		        },
		        "bar2": {
		            "precent": 80,
		            "value": 4
		        },
		        "flabel": "完成率：0%"
		    }]
             */
        	//title	xname	bar1Value	bar1Precent	bar2Value	bar2Precent
            for (LinkedHashMap<String, Object> row : data) {
                InfcChartVo vo = new InfcChartVo();
                vo.setTitle(row.get("title"));
                vo.setXname(row.containsKey("xname") ? (String) row.get("xname") : infc.getXname());
                InfcBarVo bar1=new InfcBarVo();
                vo.setBar1(bar1);    
                bar1.setValue(""+row.get("bar1Value"));
                bar1.setPrecent(""+row.get("bar1Precent"));
                InfcBarVo bar2=new InfcBarVo();
                vo.setBar2(bar2);
                bar2.setPrecent(""+row.get("bar2Precent"));
                bar2.setValue(""+row.get("bar2Value"));
                infcChartVoList.add(vo);
            }
        } else if ("map".equals(infc.getChartType())) {
            /*
            地图原生
           [
			    {
			        "name": "贵阳",
			        "value": [
			            106.63658,
			            26.654099,
			            100
			        ]
			    }
    		]
             */

        	List<LinkedHashMap<String, Object>> listRet = Lists.newArrayList();
        	//f.city_code,f.city name,f.longtitude,f.latitude ,count(p.name) value
            for (LinkedHashMap<String, Object> row : data) {
            	LinkedHashMap<String, Object> vo = new LinkedHashMap<>();     

           	 	for (String key: row.keySet()) {
           	 		vo.put(key, row.get(key));
                }
                vo.put("name", row.containsKey("name") ? (String) row.get("name") :"");
                List<Object> list = new ArrayList<Object>();
                list.add(row.get("longtitude"));
                list.add(row.get("latitude"));
                list.add(row.get("value"));
                vo.put("value", list);
                listRet.add(vo);
            }
            return listRet;
        } else if ("mapcustom".equals(infc.getChartType())) {
            /* 地图自定义
            [
				{
				"coordinates": [
					{
					"lantitude": "28.11963128",
					"longitude": "109.17829829"
					}
				],
				"id": "RcAAAAAYLGTIK8ck",
				"name": "贵州省铜仁公路管理局普通国省道提升公路连续长陡下坡路段安全通行能力专项行动",
				"type": "point"
				}
			]
             */
        	//数据库 name	number	longitude	lantitude	type

        	List<LinkedHashMap<String, Object>> listRet = Lists.newArrayList();
            for (LinkedHashMap<String, Object> row : data) {
                addMapToList(row,listRet);
            }
            return listRet;
        }else  if ("barline".equals(infc.getChartType())) {
            /*前台
            柱状图+拆线图
            [{"name": "通行收益","type": "bar","data": [{"name": "1月","value": 12.6},{"name": "2月","value": 5.9}]}
			,{"name": "路产收益","type": "line","data": [{"name": "1月","value": 2.6},{"name": "2月","value": 5.9}]}]
             
             *数据库 name,type,xname,value
             */
            for (LinkedHashMap<String, Object> row : data) {
                addBarLineToList(row,infcChartVoList);
            }
        }


        return infcChartVoList;
    }

    private void addMapToList(LinkedHashMap<String, Object> row, List<LinkedHashMap<String, Object>> infcChartVoList) {
        Object id = row.containsKey("id")? row.get("id"):"";
        Object name = row.containsKey("name")? row.get("name"):"";
        Object text = row.containsKey("text")? row.get("text"):"";
        Object type = row.containsKey("type")? row.get("type"):"";
        Object longitude = row.containsKey("longitude")? row.get("longitude"):"";
        Object lantitude = row.containsKey("lantitude")? row.get("lantitude"):"";
        //longitude	lantitude(前端接口要求)
        LinkedHashMap<String, Object> vo = new LinkedHashMap<>(); 

        if (type != null && null != name) {
            String textStr = String.valueOf(text);
            String nameStr = String.valueOf(name);
            String typeStr = String.valueOf(type);
			vo.put("name", nameStr);
			vo.put("type", typeStr);
			LinkedHashMap<String, Object> data = new LinkedHashMap<>();
			if(typeStr.toLowerCase().indexOf("point")>=0) {
				for (String key : row.keySet()) {
					data.put(key, row.get(key));
				}
			}else {
				for (String key : row.keySet()) {
					vo.put(key, row.get(key));
				}
			}
			
	        data.put("longitude", longitude);
	        data.put("lantitude", lantitude);
	        if(StringUtils.isEmpty(textStr)) {
	        	data.put("text", textStr);
	        }else {
	        	data.put("text", nameStr);
	        }
            boolean f=false;
            for (LinkedHashMap<String, Object> lvo : infcChartVoList) {
				if(lvo.get("name").toString().equalsIgnoreCase(nameStr) 
						&& lvo.get("type").toString().equalsIgnoreCase(typeStr)) {
					if(null != lvo.get("coordinates")) {
				        List<LinkedHashMap<String, Object>> list= (List<LinkedHashMap<String, Object>>)lvo.get("coordinates");
				        list.add(data);
				        f=true;
				        
					}else {
				        List<LinkedHashMap<String, Object>> list= Lists.newArrayList();
				        list.add(data);
				        f=true;
					}
					break;
				}
			}
            if(!f) {
            	List<LinkedHashMap<String, Object>> list = new ArrayList<LinkedHashMap<String,Object>>();
            	list.add(data);
            	vo.put("coordinates",list);
            	infcChartVoList.add(vo);
            }
        }
        
	}

	private void addBarLineToList(LinkedHashMap<String, Object> row, List<InfcChartVo> infcChartVoList) {

        InfcChartVo vo = new InfcChartVo();
        Object name = row.get("name");
        Object type = row.get("type");
        Object xname = row.get("xname");
        Object value = row.get("value");
        if (type != null && null != name) {
            String nameStr = String.valueOf(name);
            String typeStr = String.valueOf(type);
			vo.setName(nameStr);
			vo.setType(typeStr);
			LinkedHashMap<String, Object> data = new LinkedHashMap<>();
	        data.put("name", xname);
	        data.put("value", value);
            boolean f=false;
            for (InfcChartVo lvo : infcChartVoList) {
				if(lvo.getName().equalsIgnoreCase(nameStr) && lvo.getType().equalsIgnoreCase(typeStr)) {
			        List<LinkedHashMap<String, Object>> list= (List<LinkedHashMap<String, Object>>)lvo.getData();
			        list.add(data);
			        f=true;
				}
			}
            if(!f) {
            	List<LinkedHashMap<String, Object>> list = new ArrayList<LinkedHashMap<String,Object>>();
            	list.add(data);
            	vo.setData(list);
            	infcChartVoList.add(vo);
            }
        }
		
	}

	/**
     * 通过http请求获取数据
     * @param request req
     * @param infc infc
     * @return Object
     * @throws Exception 网络错误 或 转换JSON错误
     */
    private Object getHttpResult(HttpServletRequest request, Infc infc) throws Exception {
        if (infc.getInterfaceUrl().startsWith("http")) {
            // 0 post 1 get
            if ("0".equals(infc.getReqType())) {
                Map<String, String[]> parameterMap = request.getParameterMap();
                Map<String, Object> map = Maps.newHashMap();
                for (String key : parameterMap.keySet()) {
                    map.put(key, String.join(",", parameterMap.get(key)));
                }
                return HttpClientUtils.doPost(infc.getInterfaceUrl(), map);
            } else {
                return HttpClientUtils.doGet(infc.getInterfaceUrl());
            }
        } else {
            ArtificialHttpServletRequest req = new ArtificialHttpServletRequest("", "", infc.getInterfaceUrl());
            req.setParameters(request.getParameterMap());
            return invokeControllerByRequest.invoke(req);
        }
    }

    @Override
    public Infc getByCode(String code) {
        if (StringUtils.isNotBlank(code)) {
            return selectOne(new EntityWrapper<Infc>(Infc.class).eq("code", code).last(" limit 1"));
        }
        return null;
    }

    @Override
    public void buildInfcUrl(List<Infc> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (Infc infc : list) {
                if (StringUtils.isNotBlank(infc.getInterfaceUrl())) {
                    if (infc.getInterfaceUrl().startsWith("http")) {
                        infc.setInfcUrl(infc.getInterfaceUrl());
                    } else {
                        String baseUrl = MessageUtils.getMessage("website.base.url");
                        infc.setInfcUrl(baseUrl + infc.getInterfaceUrl());
                    }
                } else {
                    String infcUrl = MessageUtils.getMessage("website.base.url") + "/getway/network/getnetdata?code=" + infc.getCode();
                    infc.setInfcUrl(infcUrl);
                }
            }
        }
    }

    /**
     * 匹配是否为数字
     * <a>https://blog.csdn.net/u013066244/article/details/53197756</a>
     * @param str 可能为中文，也可能是-19162431.1254，不使用BigDecimal的话，变成-1.91624311254E7
     * @return
     * @author yutao
     * @date 2016年11月14日下午7:41:22
     */
    public static boolean isNumeric(String str) {
        // 该正则表达式可以匹配所有的数字 包括负数
        Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }

        Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }



    /**
     * 返回饼图格式数据
     * @param retList  [{name:xx, value:yy}]
     * @return
     */
    private List toChartBin(List<LinkedHashMap<String, Object>> retList) {
    	List ret = new ArrayList();
    	int i=0;
    	for (LinkedHashMap<String, Object> linkedHashMap : retList) {
    		if(0==i) {
    			i++;
                linkedHashMap.put("y", linkedHashMap.get("value"));
    			linkedHashMap.put("sliced", true);
    			linkedHashMap.put("selected", true);
                linkedHashMap.remove("value");
    			ret.add(linkedHashMap);
    		}else {
    			ArrayList al = new ArrayList<>();
    			al.add(linkedHashMap.get("name"));
    			al.add(linkedHashMap.get("value"));
    			ret.add(al);
    		}
		}
    	return ret;
	}
}
